/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ControlWindow.java
 *
 * Created on Mar 5, 2010, 10:40:19 PM
 */

package gui;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.tinyos.sf.SerialForwarder;

/**
 *
 * @author twentz
 */
public class ControlWindow extends javax.swing.JFrame {

    private Integer messageSize = null;

    /** Creates new form ControlWindow */
    public ControlWindow() {

        initComponents();

        messageSize = (Integer) jSpinner1.getValue();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDesktopPane1 = new javax.swing.JDesktopPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButton1 = new javax.swing.JButton();
        jSpinner1 = new javax.swing.JSpinner();
        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jButton3 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Courier New", 0, 12));
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jScrollPane1.setBounds(110, 33, 290, 160);
        jDesktopPane1.add(jScrollPane1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton1.setText("Launch Serial Forwarder");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jButton1.setBounds(90, 280, 190, 25);
        jDesktopPane1.add(jButton1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jSpinner1.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(30), Integer.valueOf(0), null, Integer.valueOf(1)));
        jSpinner1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSpinner1StateChanged(evt);
            }
        });
        jSpinner1.setBounds(280, 240, 32, 20);
        jDesktopPane1.add(jSpinner1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel1.setText("Message Size");
        jLabel1.setBounds(280, 220, 83, 15);
        jDesktopPane1.add(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton2.setText("Clear");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jButton2.setBounds(330, 260, 66, 25);
        jDesktopPane1.add(jButton2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jScrollPane3.setViewportView(jTree1);

        jScrollPane3.setBounds(0, 0, 82, 363);
        jDesktopPane1.add(jScrollPane3, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jButton3.setText("Inject Messages");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jButton3.setBounds(90, 310, 140, 25);
        jDesktopPane1.add(jButton3, javax.swing.JLayeredPane.DEFAULT_LAYER);
        jTextField1.setBounds(90, 240, 150, 19);
        jDesktopPane1.add(jTextField1, javax.swing.JLayeredPane.DEFAULT_LAYER);

        jLabel2.setText("Device Name (serial@___)");
        jLabel2.setBounds(90, 220, 154, 15);
        jDesktopPane1.add(jLabel2, javax.swing.JLayeredPane.DEFAULT_LAYER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 817, Short.MAX_VALUE)
                .addGap(24, 24, 24))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jDesktopPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 549, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

            Process pmotelist = null, pserial = null;
//            try {
//                pmotelist = Runtime.getRuntime().exec("motelist -c");
//                BufferedReader buffread = new BufferedReader (
//                                            new InputStreamReader(pmotelist.getInputStream()));
//                String motelist = buffread.readLine();
//                String[] motes = motelist.split(",");
//                String motecom;
//                if (motes.length > 2) {
//                    motecom = motes[1];
//       //             pserial = Runtime.getRuntime().exec("tos-serial-debug " + motecom + " 57600");
//       //             Thread usbreader = new Thread(new TOSBaseReader(pserial.getInputStream()));
//       //             usbreader.start();
//                } else {
//                    System.err.println("Error: Could not retrieve proper Motelist");
//                }
//            } catch (IOException ex) {
//                Logger.getLogger(ControlWindow.class.getName()).log(Level.SEVERE, null, ex);
//            }
        try {
            String motecom = jTextField1.getText() + ":tmote";
            String[] args = new String[]{"-comm", motecom};//"serial@/dev/ttyUSB1:tmote"};
            new SerialForwarder(args);
//            String s;
//            s = br.readLine();
//            while (s != null) {
//                jTextArea1.append(s + "\n");
//                s = br.readLine();
//            }
//        } catch (IOException ex) {
//            Logger.getLogger(ControlWindow.class.getName()).log(Level.SEVERE, null, ex);
//        }
        } catch (IOException ex) {
            Logger.getLogger(ControlWindow.class.getName()).log(Level.SEVERE, null, ex);
             jTextArea1.setText(ex.getMessage() + "\n" + ex.getCause().toString());
        } catch (Exception ee) {
            jTextArea1.setText(ee.getMessage() + "\n" + ee.getCause().toString());
        }
//            String s;
//            s = br.readLine();
//            while (s != null) {
//                jTextArea1.append(s + "\n");
//                s = br.readLine();
//            }
//        } catch (IOException ex) {
//            Logger.getLogger(ControlWindow.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jSpinner1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSpinner1StateChanged
        messageSize = (Integer) jSpinner1.getValue();
    }//GEN-LAST:event_jSpinner1StateChanged

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        jTextArea1.setText("");
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        InputFrame anotherFrame = new InputFrame();
        anotherFrame.pack();
        anotherFrame.setVisible(true);
        this.jDesktopPane1.add(anotherFrame);
    }//GEN-LAST:event_jButton3ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ControlWindow().setVisible(true);
            }
        });
    }

    public class TOSBaseReader implements Runnable {

        BufferedReader br;
        InputStreamReader isr;
        ByteArrayInputStream bais;
        InputStream iss;
   //     SerialPortEvent.BI;
        


        public TOSBaseReader(InputStream inputstream) {
            
            isr = new InputStreamReader(inputstream);
            br = new BufferedReader(isr);
            iss = inputstream;
        }

        public void run() {



//                if (isr.ready()) {
//                    isr.read(chararr);
//                    jTextArea1.append(chararr.toString());
//                } else {
//                    System.out.println("isr not ready");
//                }
//                while (true) {
//                    if(isr.ready()){
//                    isr.read(chararr);
//                    s = new String(chararr);
//                    jTextArea1.append(s + "\n");
//                    }
//                }
            String s, sbuffin, sbuffapp;
            try {
                s = br.readLine();
                while (s != null) {
                    sbuffapp = "";
                    while (s.length() > messageSize) {
                        sbuffin = s.substring(0, messageSize);
                        sbuffapp += sbuffin + "\n";
                        s = s.substring(messageSize);
                    }
                    if (s.length() > 0) {
                        sbuffapp += s + "\n";
                    }

                    jTextArea1.append(sbuffapp);
                    s = br.readLine();
                }
            } catch (IOException ex) {
                Logger.getLogger(ControlWindow.class.getName()).log(Level.SEVERE, null, ex);
            }


//            String s;
//            try {
//                s = br.readLine();
//                while (s != null) {
//                    jTextArea1.append(s + "\n");
//                    s = br.readLine();
//                }
//            } catch (IOException ex) {
//                Logger.getLogger(ControlWindow.class.getName()).log(Level.SEVERE, null, ex);
//            }
        }

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JDesktopPane jDesktopPane1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTree jTree1;
    // End of variables declaration//GEN-END:variables

}
